﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.IO;
using System.Xml;
using System.Text.RegularExpressions;

namespace Magento.Generation
{
    class WebAPI : Abstract
    {
        public bool readAndCreate(string dir)
        {
            if (!Directory.Exists(dir))
            {
                this.addMessage(dir + " Directory not exist.");
                return false;
            }

            string module_name = this.getModuleName(dir);
            if (module_name == null)
                return false;

            string[] files = Directory.GetFiles(dir, "webapi.xml", SearchOption.AllDirectories);

            if (files.Length == 0)
            {
                this.addMessage("webapi.xml file not exist.");
                return false;
            }

            foreach (string file in files)
            {
                if (!this.createFileForXml(dir, module_name, file))
                {
                    return false;
                }
            }

            return true;
        }

        protected bool createFileForXml(string dir, string module_name, string path)
        {
            XmlDocument doc = new XmlDocument();
            XmlElement element;
            doc.Load(path);
            XmlNamespaceManager nsp = new XmlNamespaceManager(doc.NameTable);
            nsp.AddNamespace("xsi", "http://www.w3.org/2001/XMLSchema-instance");
            
            foreach (XmlNode _node in doc.SelectNodes(@"//routes/route/service"))
            {
                element = (XmlElement)_node;
                var phpInterface = element.GetAttribute("class").ToString();
                var phpMethod = element.GetAttribute("method").ToString();
                var methods = new List<String>();

                if (phpMethod != null) {
                    methods.Add(phpMethod);
                }

                if (!phpInterface.StartsWith(module_name.Replace("_", @"\")))
                {
                    this.addMessage($"{phpInterface} 此类并不属于{module_name} 之下");
                    return false;
                }

                var _filePath = Regex.Replace(phpInterface, "^" + module_name.Replace("_", @"\\"), dir) + ".php";

                // create file
                var php = new PHP();
                if (php.setFullClassName(phpInterface).setType("interface").setClassComment("@api").toFile(_filePath)) {
                    this.addMessage($"{_filePath} created");
                }
            }
            
            return true;
        }
    }
}
